package logic

import (
	"context"
	"fmt"
	"github.com/zeromicro/go-zero/core/stores/sqlx"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"
	"order_rpc/pkg"
	"time"

	"order_rpc/internal/svc"
	"order_rpc/pb/order"

	"github.com/zeromicro/go-zero/core/logx"
)

type CreateOrderLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewCreateOrderLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CreateOrderLogic {
	return &CreateOrderLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *CreateOrderLogic) CreateOrder(in *order.OrderInfo) (*order.OrderInfo, error) {
	if in.UserId == 0 {
		return nil, status.Error(codes.InvalidArgument, "用户ID不能为空")
	}
	if len(in.Goods) == 0 {
		return nil, status.Error(codes.InvalidArgument, "商品列表不能为空")
	}

	//orderID := pkg.GenerateSnowflakeId()
	orderID := time.Now().Unix()
	orderQuery := `INSERT INTO orders (user_id, order_id, order_status, order_total, create_time) VALUES (?, ?, ?, ?, ?)`
	goodsQuery := `INSERT INTO order_goods (order_id, good_id, good_name, good_price, good_count, good_cost) VALUES (?, ?, ?, ?, ?, ?)`
	err := l.svcCtx.Conn.TransactCtx(l.ctx, func(ctx context.Context, session sqlx.Session) error {
		_, err := session.ExecCtx(ctx, orderQuery, in.GetUserId(), orderID, pkg.OrderStatusPending, in.OrderTotal, time.Now().Unix())
		if err != nil {
			l.Logger.Errorf("CreateOrder failed: user_id=%d, order_id=%d, err=%v", in.UserId, orderID, err)
			return fmt.Errorf("创建订单失败: %w", err)
		}

		for _, good := range in.GetGoods() {
			goodID := good.GoodId
			goodName := good.GoodName
			goodPrice := good.GoodPrice
			goodCount := good.GoodCount
			goodCost := good.GoodCost
			_, err = session.ExecCtx(ctx, goodsQuery, orderID, goodID, goodName, goodPrice, goodCount, goodCost)
			if err != nil {
				l.Logger.Errorf("CreateOrderGood failed: user_id=%d, order_id=%d, good_id=%d, good_name=%s, good_price=%d, "+
					"good_count=%d, err=%v", in.UserId, orderID, goodID, goodName, goodPrice, goodCount, goodCost, err)
				return fmt.Errorf("添加订单商品失败: %w", err)
			}
		}
		return nil
	})

	if err != nil {
		return nil, err
	}
	return &order.OrderInfo{OrderId: orderID}, nil
}
